#include "StdAfx.h"
#include "reghandler.h"
#include <Process.h>

namespace gloox
{
RegHandler::RegHandler(RegResultHandler* regResult):
m_regResult(regResult), m_client(NULL), m_reg(NULL)
{
}

RegHandler::~RegHandler(void)
{
	cleanup();
}

void RegHandler::start(const RegistrationFields& regFields, string& server, LogHandler* logHandler)
{
	m_regFields = regFields;
	m_client = new Client(server);
	m_client->disableRoster();
	m_client->setForceNonSasl();
	m_client->registerConnectionListener(this);

	m_reg = new Registration(m_client);
	m_reg->registerRegistrationHandler(this);

	m_client->logInstance().registerLogHandler(LogLevelDebug, LogAreaAll, logHandler);

	HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, registerThread, this, 0, NULL);
	CloseHandle(hThread);
	
}

unsigned int RegHandler::registerThread(void *pvoid)
{
	RegHandler * pRegHander = static_cast<RegHandler*>(pvoid);
	if (pRegHander == NULL) return 1;
	
	pRegHander->m_client->connect();
	pRegHander->cleanup();

	return 0;
}

void RegHandler::onConnect()
{
	if (m_reg != NULL)
		m_reg->fetchRegistrationFields();
}

void RegHandler::onDisconnect(ConnectionError e)
{
}

bool RegHandler::onTLSConnect(const CertInfo& info)
{
	return true;
}

void RegHandler::handleRegistrationFields(const JID& from, int fields, std::string instructions)
{
	m_regFields.username = JID::escapeNode(m_regFields.username);
	m_reg->createAccount(fields, m_regFields);
}

void RegHandler::handleRegistrationResult(const JID& from, RegistrationResult result)
{
	if (m_regResult != NULL)
		m_regResult->handleRegistrationResult(JID::unescapeNode(m_regFields.username), m_regFields.password, result);
	m_client->disconnect();
}

void RegHandler::handleAlreadyRegistered(const JID& from)
{
	if (m_regResult != NULL)
		m_regResult->handleAlreadyRegistered(JID::unescapeNode(m_regFields.username));
}

void RegHandler::handleDataForm(const JID& from, const DataForm& form)
{

}

void RegHandler::handleOOB(const JID& from, const OOB& oob)
{

}

void RegHandler::cleanup()
{
	if (m_reg != NULL)
	{
		delete m_reg;
		m_reg = NULL;
	}
	if (m_client != NULL)
	{
		delete m_client;
		m_client = NULL;
	}	
}

}